<template>
  <a-modal
    :title="$t('app.setting.modal.add')"
    :visible="modalInfoAdd.visible"
    :width="800"
    footer=""
    @cancel="modalFooter(0)"
    :maskClosable="false"
  >
    <!-- loading -->
    <a-spin v-if="!modalInfoAdd.sourceData" class="spin"/>
    <!-- loading end -->

    <div v-if="modalInfoAdd.sourceData">
      <div v-for="( itemWrap, indexWrap) in modalInfoAdd.sourceData" :key="indexWrap" style="margin-top: 20px;">
        <div v-for="(item, index) in itemWrap" :key="index">
          <ModifyForm
            @formValidateResult="formValidateResult"
            :componentsObject="{
              title: item.title,
              keys: item.keys,
              placeholder: item.placeholder,
              type: item.type,
              value: item.value,
              index: index,
              indexWrap: indexWrap,
              validateObj: item.validateObj
            }"
            :key="Math.random()"
          ></ModifyForm>
        </div>
        <a-row style="padding-bottom: 20px;">
          <a-col :span="5"></a-col>
          <a-col :span="12">
            <a-popconfirm
              title="确认删除本项信息?"
              ok-text="删除"
              cancel-text="取消"
              @confirm=" () => popConfirm(indexWrap)"
              @cancel="popCancel"
            >
              <span style="cursor: pointer;">
                <span>删除本项&nbsp;</span>
                <a-icon type="delete" />
              </span>
            </a-popconfirm>
          </a-col>
        </a-row>
        <!-- 临时的分割线-可保留  样式根据需要随时进行调整处理 -->
        <div style="width: 80%; border-bottom-style: dashed; color: #ccc; border-bottom-width: 1px; margin: 0 auto;"> </div>
        
      </div>

      <a-row style="margin-top: 20px;">
        <a-col :span="5" style="text-align: right; cursor: pointer;">
          <span @click="addMore">增加多个&nbsp;<a-icon type="plus-circle" /></span>
        </a-col>
        <a-col :span="12"></a-col>
      </a-row>

    </div>
    <!-- 底部按钮 -->
    <ModalFooter @modalFooter="modalFooter" ref="modalFooterRef"></ModalFooter>
  </a-modal>
</template>

<script>

// 引入展示结构组件
import ModifyForm from './ModifyForm'
// 引入新增的信息和数据结构
import { getAddModalInfo,  addItem} from '../../api/data'
// 引入 store
import store from '@/store'
// 引入公共的底部按钮（确定+取消）
import ModalFooter from './ModalFooter'

export default {
  name: 'Modal',
  components: {
    ModifyForm,
    ModalFooter
  },
  props: {
    modalInfoAdd: Object,
    // modalInfoAdd:{
    //   visible: false,  // false不显示， true显示
    //   multi: 1,        // 2-多操作  1-单操作
    //   sourceData: '',  // 源数据
    // }
    requestUrl: Object,
    modalAddStructure: Object,
  },
  data () {
    return {
      modalInfoAddValidate: [],
      visible: true,
      initValidate: true,
      // currentFormData < - Array - >动态表单的数据的存储
      currentFormData: [],
      currentInitStructure: '',
    }
  },

  created(){},
  mounted(){
    // 每次进入重置数据
    this.modalInfoAdd.sourceData = '' 
    // 初始结构化的数据
    this.getAddModalInfo();   
    
  },
  
  methods: {


    // 删除确认处理
    popConfirm(index) {
      // 至少保留一个数据对象
      if(this.modalInfoAdd.sourceData.length === 1){
        this.$message.warning("删除失败！至少需要保留一个添加项！");
      }else{
        // 删除数据结构
        this.modalInfoAdd.sourceData.splice(index,1);
        // 删除已经存储的数据
        this.currentFormData.splice(index, 1)
        // 重新赋值处理
        this.modalInfoAdd.sourceData.map((itemWrap, indexWrap)=>{
          itemWrap.map((item, index)=>{
            this.modalInfoAdd.sourceData[indexWrap][index][item.keys] = this.currentFormData[indexWrap][item.keys]
            this.modalInfoAdd.sourceData[indexWrap][index].value = this.currentFormData[indexWrap][item.keys]
          })
        })
      }
    },

    // 删除取消处理
    popCancel(e) {
      this.$message.error('执行了取消');
    },

    // 点击增加更多，增加新的数据结构
    addMore(){
      // 增加结构
      this.getAddModalInfo();
      // 存储数据
      this.modalInfoAdd.sourceData.map((itemWrap, indexWrap)=>{
        if(indexWrap + 1 < this.modalInfoAdd.sourceData.length){
          itemWrap.map((item, index)=>{ // 表单 value 值记录存储
            this.modalInfoAdd.sourceData[indexWrap][index][item.keys] = this.currentFormData[indexWrap][item.keys]
            this.modalInfoAdd.sourceData[indexWrap][index].value = this.currentFormData[indexWrap][item.keys]
          })
        }
      })
      setTimeout(()=>{
        console.log("测试下我要的数据---this.modalInfoAdd.sourceData---", this.modalInfoAdd.sourceData);
      }, 2000)
    },

    // 新增数据的请求
    async addItem(parameter){
      let responseData = await addItem(parameter, this.requestUrl.add)
      if(responseData.code){
        this.$message.success("新增成功");
      }else{
        this.$message.error("新增失败");
      }
      this.modalInfoAdd.visible = false
    },

    // modal 底部确定和退出
    modalFooter(e){
      if(e){  // 确定
        this.addSubmit()
      }else{ // 退出
        this.modalInfoAdd.visible = false
      }
    },

    /**
     * 每个单独的组件的验证的结果
     * @return: e=> <object> { index: number, seniorValue: string, through: boolean }
     */
    formValidateResult(e){
      console.log("参数验证结果接收测试-e-", e);
      if(!e.through){
        this.initValidate = false
      }else{
        this.currentFormData[e.indexWrap][e.keys]  = e.seniorValue
      }
    },

    // 点击确定
    addSubmit(){
      this.initValidate = true
      this.$store.dispatch('CheckFormTransform')
      setTimeout(()=>{
        if(this.initValidate){
          // this.currentFormData => 新增的数据的信息, 格式以对象数组的形式存储 [{},{}]
          this.addItem(this.currentFormData)
        }else{
          this.$message.warning("信息填写有误，请按照提示修改已经填写的信息");
        }
        this.$refs.modalFooterRef.closeLoading();
      }, 500)
    },

    // 请求新增的数据结构
    getAddModalInfo(){
      let resultArr = []
      let valueObj = {}
      this.modalAddStructure.map((item, index)=>{
        let tempObj = {
          title: item.title,
          keys: item.keys,
          placeholder: item.placeholder,
          type: item.addType,
          value: item.value,
          validateObj: item.validateObj
        }
        resultArr.push(tempObj)
        this.modalInfoAddValidate.push(false)
        valueObj[item.keys] = ''
      })
      
      this.currentFormData.push(valueObj)
      if(!this.modalInfoAdd.sourceData){
        this.modalInfoAdd.sourceData = []
      }
      this.modalInfoAdd.sourceData.push(resultArr)
    },

    // 展示 modal
    showModal() {
      this.modalInfoAdd.visible = true;
    },
    
    handleOk(e) {
      this.confirmLoading = true;
      setTimeout(() => {
        this.modalInfoAdd.visible = false;
        this.confirmLoading = false;
      }, 2000);
    },

    handleCancel(e) {
      this.modalInfoAdd.visible = false;
    }
  },
  watch: {
    
  }
}
</script>

<style lang="less" scoped>
.spin {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
